{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [],
   "source": [
    "import numpy as np\n",
    "from scipy.stats import entropy"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Specifically, the Kullback–Leibler divergence from $Q$ to $P$, denoted  $D_{KL}({P} || {Q})$, is\n",
    "a measure of the information gained when one revises one's beliefs from the\n",
    "prior probability distribution $Q$ to the posterior probability distribution $P$. In\n",
    "other words, it is the amount of information lost when $Q$ is used to approximate\n",
    "$P$."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [],
   "source": [
    "def kl(p, q):\n",
    "    \"\"\"Kullback-Leibler divergence D(P || Q) for discrete distributions\n",
    "    Parameters\n",
    "    ----------\n",
    "    p, q : array-like, dtype=float, shape=n\n",
    "    Discrete probability distributions.\n",
    "    \"\"\"\n",
    "    p = np.asarray(p, dtype=np.float)\n",
    "    q = np.asarray(q, dtype=np.float)\n",
    "\n",
    "    return np.sum(np.where(p != 0, p * np.log(p / q), 0))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [],
   "source": [
    "def kl(p, q):\n",
    "    \"\"\"Kullback-Leibler divergence D(P || Q) for discrete distributions\n",
    "    Parameters\n",
    "    ----------\n",
    "    p, q : array-like, dtype=float, shape=n\n",
    "    Discrete probability distributions.\n",
    "    \"\"\"\n",
    "    p = np.asarray(p, dtype=np.float)\n",
    "    q = np.asarray(q, dtype=np.float)\n",
    "\n",
    "    return np.sum(np.where(p != 0, p * np.log(p / q), 0))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [],
   "source": [
    "p = [0.1, 0.9]\n",
    "q = [0.1, 0.9]\n",
    "assert entropy(p, q) == kl(p, q)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Thank you [swayson](https://gist.github.com/swayson/86c296aa354a555536e6765bbe726ff7)!"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.6.7"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
